package cn.player.download;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class M3u8FileHelper {


    /**
     * 组装不同码率播放地址
     *
     * @param hlsUrl    主地址
     * @param hlsSubUrl 不同码率地址
     * @return
     */
    public static String getTsDownloadUrl(String hlsUrl, String hlsSubUrl) {
        if (hlsUrl == null || "".equals(hlsUrl.trim())) {
            return null;
        }

        if (!hlsUrl.startsWith("http://") && !hlsUrl.startsWith("https://")) {
            return null;
        }
        //    http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/6295d93f4e964903bc5bd89ab8d35b5f/main.m3u8
        String protocol = hlsUrl.substring(0, hlsUrl.indexOf(":"));//http
        String strtoken = hlsUrl.substring(hlsUrl.indexOf("/") + 2);
        int domainIdx = strtoken.indexOf("/");

        String domainName = "";
        if (domainIdx != -1) {
            domainName = strtoken.substring(0, domainIdx); //       asp.cntv.lxdns.com
        } else {
            return null;
        }

        String realUrl = null;
        if (hlsSubUrl.startsWith("http://") || hlsSubUrl.startsWith("https://")) {
            // contain whole real url
            realUrl = hlsSubUrl;
        } else if (hlsSubUrl.startsWith("/")) {
            // domain + subUrl;
            realUrl = protocol + "://" + domainName + hlsSubUrl;
        } else {
            // mainUrl + subUrl;
            realUrl = hlsUrl.substring(0, hlsUrl.lastIndexOf("/")) + "/" + hlsSubUrl;
        }
//		LogUtil.i("zl","realUrl = "  + realUrl);
        return realUrl;
    }


    /**
     * 根据每个码率地址获取ts文件地址列表,并更新m3u8文件内容
     *
     * @param m3u8Url      传入的码率地址
     * @param m3u8FilePath m3u8文件路径
     * @return
     */
    public static List<String> getM3u8VideoUrlList(String m3u8Url, String m3u8FilePath) {

        List<String> m3u8UrlList = new ArrayList<String>();
        StringBuilder sbTemp = new StringBuilder();

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            fis = new FileInputStream(m3u8FilePath);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);

            for (String line = br.readLine(); line != null; line = br.readLine()) {
                if (line.endsWith(".ts")) {
                    m3u8UrlList.add(getTsDownloadUrl(m3u8Url, line));
                    sbTemp.append(line.substring(line.lastIndexOf("/") + 1));
                } else {
                    sbTemp.append(line);
                }
                sbTemp.append("\n");
            }

//            sbTemp.delete(sbTemp.lastIndexOf("\n"), sbTemp.length() - 1);
            fos = new FileOutputStream(m3u8FilePath);
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            bw.write(sbTemp.toString(), 0, sbTemp.length());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                    br = null;
                }
                if (isr != null) {
                    isr.close();
                    isr = null;
                }
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
                if (bw != null) {
                    bw.close();
                    bw = null;
                }
                if (osw != null) {
                    osw.close();
                    osw = null;
                }
                if (fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return m3u8UrlList;
    }
}
